<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单详情</title>
    <link rel="stylesheet" href="../js/element-ui/lib/theme-chalk/index.css">
    <style>
        body {
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f7fa;
        }
        .detail-container {
            max-width: 1000px;
            margin: 0 auto;
        }
        .card {
            background: #fff;
            border-radius: 4px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        .card-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }
        .info-row {
            display: flex;
            margin-bottom: 10px;
        }
        .info-label {
            width: 120px;
            color: #909399;
        }
        .info-value {
            flex: 1;
            color: #606266;
        }
        .status-badge {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 3px;
            font-size: 12px;
        }
        .status-pending_payment {
            background-color: #fff1f0;
            color: #f5222d;
        }
        .status-processing {
            background-color: #fff7e6;
            color: #fa8c16;
        }
        .status-shipped {
            background-color: #e6f7ff;
            color: #1890ff;
        }
        .status-completed {
            background-color: #f6ffed;
            color: #52c41a;
        }
        .product-image {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 4px;
        }
        .address-info {
            line-height: 1.6;
        }
        .total-amount {
            font-size: 16px;
            font-weight: bold;
            color: #f56c6c;
        }
        /* 单据对话框样式 */
        .bill-dialog .el-dialog__body {
            padding: 10px 20px;
        }

        .bill-container {
            font-family: "Microsoft YaHei", Arial, sans-serif;
            padding: 10px;
            color: #333;
        }

        .bill-header {
            margin-bottom: 20px;
            text-align: center;
            border-bottom: 2px solid #000;
            padding-bottom: 10px;
        }

        .bill-header h2 {
            margin: 0;
            font-size: 24px;
            font-weight: bold;
        }

        .bill-header h3 {
            margin: 5px 0 0;
            font-size: 18px;
        }

        .bill-info {
            text-align: left;
            margin: 15px 0;
            line-height: 1.8;
            font-size: 14px;
        }

        .bill-info div {
            display: flex;
        }

        .bill-info strong {
            min-width: 100px;
            display: inline-block;
        }

        .bill-table {
            margin: 15px 0;
            font-size: 14px;
        }

        .bill-table th {
            background-color: #f5f5f5 !important;
            font-weight: bold;
            text-align: center !important;
        }

        .bill-footer {
            text-align: right;
            font-size: 16px;
            font-weight: bold;
            margin-top: 20px;
            border-top: 1px solid #ddd;
            padding-top: 10px;
        }

        .total-amount {
            font-size: 18px;
        }

        /* 打印样式 */
        @media print {
            /* 重置表格布局 */
            .bill-table {
                border-collapse: collapse !important;
                table-layout: fixed !important;
                width: 100% !important;
                box-sizing: border-box !important;
            }

            /* 强制所有列使用相同盒模型 */
            .bill-table th,
            .bill-table td {
                box-sizing: border-box !important;
                border: 1px solid #333 !important;
                overflow: hidden !important;
                font-family: "Microsoft YaHei" !important;
                font-size: 10.5pt !important;
            }

            /* 表头特殊样式 */
            .bill-table th {
                background-color: #f8f9fa !important;
                padding: 10px 5px !important;
                font-weight: 600 !important;
                text-align: center !important;
            }

            /* 数据列通用样式 */
            .bill-table td {
                padding: 8px 5px !important;
                vertical-align: middle !important;
            }

            /* 精确列宽设置（总宽度100%） */
            .bill-table col:nth-child(1) { width: 7%; }   /* 行号 */
            .bill-table col:nth-child(2) { width: 15%; }  /* 物料代码 */
            .bill-table col:nth-child(3) { width: 38%; }  /* 物料名称 */
            .bill-table col:nth-child(4) { width: 12%; }  /* 数量 */
            .bill-table col:nth-child(5) { width: 14%; }  /* 单价 */
            .bill-table col:nth-child(6) { width: 14%; }  /* 金额 */

            /* 特殊列对齐调整 */
            .bill-table td:nth-child(3) {
                text-align: left !important;
                padding-left: 10px !important;
            }
            .bill-table td:nth-child(5),
            .bill-table td:nth-child(6) {
                text-align: right !important;
                padding-right: 12px !important;
                font-family: "Courier New" !important; /* 等宽数字 */
            }

            /* 强制打印样式生效 */
            .bill-table {
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
        }
    </style>
</head>
<body>
<div id="app">
    <div class="detail-container" v-loading="loading" element-loading-text="拼命加载中...">
        <el-button type="primary" icon="el-icon-arrow-left" @click="goBack">返回订单列表</el-button>

        <!-- 订单基本信息卡片 -->
        <div class="card">
            <div class="card-title">订单信息</div>
            <div class="info-row">
                <div class="info-label">订单编号：</div>
                <div class="info-value">{{ order.orderNumber }}</div>
            </div>
            <div class="info-row">
                <div class="info-label">订单状态：</div>
                <div class="info-value">
            <span class="status-badge" :class="'status-' + order.status">
                {{ formatStatus(order.status) }}
            </span>
                </div>
            </div>
            <div class="info-row">
                <div class="info-label">下单时间：</div>
                <div class="info-value">{{ formatDate(order.createdAt) }}</div>
            </div>
            <div class="info-row">
                <div class="info-label">订单金额：</div>
                <div class="info-value total-amount">¥{{ formatAmount(order.totalAmount) }}</div>
            </div>
            <div class="info-row">
                <div class="info-label">配送方式：</div>
                <div class="info-value">{{ formatShippingMethod(order.shippingMethod) }}</div>
            </div>
            <div class="info-row" v-if="order.shippingMethod === 'delivery'">
                <div class="info-label">物流单号：</div>
                <div class="info-value">{{ order.trackingNumber || '暂无' }}</div>
            </div>
            <div class="info-row">
                <div class="info-label">支付方式：</div>
                <div class="info-value">{{ formatPaymentMethod(order.paymentMethod) }}</div>
            </div>
            <div class="info-row">
                <div class="info-label">订单备注：</div>
                <div class="info-value">{{ order.remark || '无' }}</div>
            </div>
        </div>

        <!-- 收货地址卡片 -->
        <div class="card" v-if="order.shippingMethod === 'delivery' && shippingAddress">
            <div class="card-title">收货信息</div>
            <div class="address-info">
                <div><strong>收件人：</strong>{{ shippingAddress.receiverName }}</div>
                <div><strong>联系电话：</strong>{{ shippingAddress.phone }}</div>
                <div><strong>所在地区：</strong>{{ order.province }} {{ order.city }} {{ order.district }}</div>
                <div><strong>详细地址：</strong>{{ shippingAddress.detailAddress }}</div>
            </div>
        </div>

        <!-- 自提信息卡片 -->
        <div class="card" v-if="order.shippingMethod === 'self_pickup'">
            <div class="card-title">自提信息</div>
            <div class="address-info">
                <div><strong>自提码：</strong>{{ order.pickupCode || '暂无' }}</div>
                <div><strong>自提点地址：</strong></div>
                <div><strong>营业时间：</strong></div>
            </div>
        </div>

        <!-- 订单商品列表卡片 -->
        <div class="card">
            <div class="card-title">商品清单</div>
            <el-table :data="orderItems" style="width: 100%" border>
                <el-table-column label="商品信息" width="300">
                    <template slot-scope="scope">
                        <div style="display: flex; align-items: center;">
                            <img :src="scope.row.productImage || 'https://via.placeholder.com/60'" class="product-image">
                            <div style="margin-left: 10px;">
                                <div>{{ scope.row.productName }}</div>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="productNumber" label="商品货号" width="150"></el-table-column>
                <el-table-column prop="quantity" label="数量" width="100" align="center"></el-table-column>
                <el-table-column label="单价" width="120" align="right">
                    <template slot-scope="scope">
                        ¥{{ formatAmount(scope.row.unitPrice) }}
                    </template>
                </el-table-column>
                <el-table-column label="小计" width="120" align="right">
                    <template slot-scope="scope">
                        <span class="total-amount">¥{{ formatAmount(scope.row.totalPrice) }}</span>
                    </template>
                </el-table-column>
            </el-table>

            <div style="text-align: right; margin-top: 20px;">
                <div style="font-size: 14px; color: #606266; margin-bottom: 5px;">
                    共 {{ totalQuantity }} 件商品
                </div>
                <div style="font-size: 16px;">
                    合计：<span class="total-amount">¥{{ formatAmount(order.totalAmount) }}</span>
                </div>
            </div>
            <div style="text-align: right; margin-top: 20px;">
                <el-button type="primary" @click="showBillDialog" size="medium">查看单据</el-button>
            </div>
        </div>

    </div>

    <!-- 单据对话框 -->
    <el-dialog
            title="订单商品清单"
            :visible.sync="billDialogVisible"
            width="80%"
            top="5vh"
            class="bill-dialog"
            v-if="billDialogVisible">

        <div class="bill-container">
            <div class="bill-header">
                <h2>订单单据</h2>
                <h3>订单物料清单</h3>
                <div class="bill-info">
                    <div><strong>订单号：</strong> {{ order.orderNumber }}</div>
                    <div><strong>客户：</strong> {{ order.companyName }}</div>
                    <div><strong>订单创建时间：</strong> {{ formatDate(order.createdAt) }}</div>
                    <div><strong>收货地址：</strong> {{ formatFullAddress(order) }}</div>
                    <div><strong>备注：</strong> {{ order.remark || '无' }}</div>
                </div>
            </div>

            <el-table
                    :data="orderItems"
                    border
                    style="width: 100%"
                    class="bill-table">
                <el-table-column
                        prop="productId"
                        label="行号"
                        width="50"
                        align="center">
                    <template slot-scope="scope">{{ scope.$index + 1 }}</template>
                </el-table-column>
                <el-table-column
                        prop="productNumber"
                        label="物料代码"
                        width="100"
                        align="center"></el-table-column>
                <el-table-column
                        prop="productName"
                        label="物料名称"
                        width="250"
                        align="left"></el-table-column>
                <el-table-column
                        prop="quantity"
                        label="订单数量"
                        width="80"
                        align="center"></el-table-column>
                <el-table-column
                        prop="unitPrice"
                        label="单价"
                        width="80"
                        align="right">
                    <template slot-scope="scope">
                        ¥{{ formatAmount(scope.row.unitPrice) }}
                    </template>
                </el-table-column>
                <el-table-column
                        prop="totalPrice"
                        label="金额"
                        width="100"
                        align="right">
                    <template slot-scope="scope">
                        ¥{{ formatAmount(scope.row.totalPrice) }}
                    </template>
                </el-table-column>
            </el-table>

            <div class="bill-footer">
                <div class="total-amount">合计：¥{{ formatAmount(order.totalAmount) }}</div>
            </div>

            <div class="company-info">
                <div style="font-size: 14pt; font-weight: bold;">公司名称</div>
                <div>公司地址：XX省XX市XX区XX路XX号</div>
                <div>联系电话：400-XXX-XXXX | 邮箱：service@company.com</div>
            </div>

        </div>

        <span slot="footer" class="dialog-footer">
        <el-button @click="billDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="printBill" v-if="!isPrinting">打印</el-button>
    </span>
    </el-dialog>

</div>

<script src="../js/vue.js"></script>
<script src="../js/axios-0.18.0.js"></script>
<script src="../js/element-ui/lib/index.js"></script>

<script>
    // 创建axios实例
    const api = axios.create({
        baseURL: '/',
        timeout: 10000
    });

    new Vue({
        el: '#app',
        data() {
            return {
                order: {
                    orderNumber: '',
                    status: '',
                    createdAt: '',
                    totalAmount: 0,
                    shippingMethod: '',
                    trackingNumber: '',
                    pickupCode: '',
                    paymentMethod: '',
                    remark: ''
                },
                orderItems: [],
                shippingAddress: null,
                loading: true,
                billDialogVisible: false,
                isPrinting: false
            }

        },
        computed: {
            totalQuantity() {
                return this.orderItems.reduce((total, item) => total + item.quantity, 0);
            }
        },
        created() {
            this.fetchOrderDetail();
        },
        methods: {
            async fetchOrderDetail() {
                this.loading = true;
                try {
                    const urlParams = new URLSearchParams(window.location.search);
                    const orderNumber = urlParams.get('orderNumber');

                    const [orderRes, itemsRes, addressRes] = await Promise.all([
                        api.get('/user/getOrderDetail', { params: { orderNumber } }),
                        api.get('/user/getOrderItems', { params: { orderNumber } }),
                        api.get('/user/getOrderShippingAddress', { params: { orderNumber } })
                    ]);

                    // 统一处理响应结构
                    this.order = orderRes.data?.data || {};  // 获取data字段
                    this.orderItems = itemsRes.data?.data || [];  // 确保是数组
                    this.shippingAddress = addressRes.data?.data || null;

                } catch (error) {
                    console.error('Error:', error);
                    this.$message.error('加载失败: ' + (error.response?.data?.msg || error.message));
                } finally {
                    this.loading = false;
                }
            },
            formatStatus(status) {
                const statusMap = {
                    pending_payment: '待付款',
                    processing: '处理中',
                    shipped: '已发货',
                    completed: '已完成',
                    cancelled: '已取消'
                };
                return statusMap[status] || status;
            },
            formatDate(dateStr) {
                if (!dateStr) return '';
                const date = new Date(dateStr);
                return date.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit',
                    hour12: false
                }).replace(/\//g, '-');
            },
            formatAmount(amount) {
                if (amount === null || amount === undefined) return '0.00';
                return parseFloat(amount).toFixed(2);
            },
            formatShippingMethod(method) {
                const methodMap = {
                    delivery: '快递配送',
                    self_pickup: '门店自提'
                };
                return methodMap[method] || method;
            },
            formatPaymentMethod(method) {
                const methodMap = {
                    alipay: '支付宝',
                    wechat_pay: '微信支付',
                    credit_card: '信用卡'
                };
                return methodMap[method] || method || '未支付';
            },
            formatFullAddress(address) {
                if (!address) return '';
                const { province, city, district, detailAddress } = address;
                return `${province || ''}${city || ''}${district || ''}${detailAddress || ''}`;
            },
            goBack() {
                window.parent.postMessage({
                    type: 'changePage',
                    url: 'myorders.html'
                }, '*');
            },
            showBillDialog() {
                this.billDialogVisible = true;
            },

            printBill() {
                if (this.isPrinting) return;
                this.isPrinting = true;

                // 创建打印内容副本
                const printContent = document.querySelector('.bill-container').cloneNode(true);

                // 添加页码脚本
                const script = document.createElement('script');
                script.innerHTML = `
        // 添加页码
        function addPageNumbers() {
            const totalPages = Math.ceil(document.body.scrollHeight / 1000);
            document.querySelectorAll('.totalPages').forEach(el => {
                el.textContent = totalPages;
            });
            document.querySelectorAll('.pageNumber').forEach((el, i) => {
                el.textContent = i + 1;
            });
        }
        window.onafterprint = function() {
            // 打印完成后关闭对话框
            window.parent.postMessage({type: 'closePrintDialog'}, '*');
        };
        addPageNumbers();
    `;

                // 创建iframe
                const printFrame = document.createElement('iframe');
                printFrame.style.position = 'absolute';
                printFrame.style.width = '0';
                printFrame.style.height = '0';
                printFrame.style.border = 'none';
                printFrame.style.left = '-9999px';

                printFrame.onload = function() {
                    const doc = printFrame.contentDocument || printFrame.contentWindow.document;
                    doc.head.innerHTML = `
            <title>订单单据 - ${this.order.orderNumber}</title>
            <style>
                ${document.querySelector('style').innerHTML}
            </style>
        `;
                    doc.body.appendChild(printContent);
                    doc.body.appendChild(script);

                    // 延迟打印确保内容加载完成
                    setTimeout(() => {
                        printFrame.contentWindow.focus();
                        printFrame.contentWindow.print();

                        // 清理
                        setTimeout(() => {
                            document.body.removeChild(printFrame);
                            this.isPrinting = false;
                        }, 1000);
                    }, 500);
                }.bind(this);

                document.body.appendChild(printFrame);
            },
            formatFullAddress(row) {
                const { province, city, district, detailAddress } = row;
                let fullAddress = [];

                if (province && (!city || city !== province)) {
                    fullAddress.push(province);
                }

                if (city && city !== "市辖区") {
                    fullAddress.push(city);
                }

                if (district) {
                    fullAddress.push(district);
                }

                if (detailAddress) {
                    fullAddress.push(detailAddress);
                }

                return fullAddress.join("") || "无地址信息";
            }
        }
    });
</script>
</body>
</html>